package com.mercury.rabbitmq.config.delay;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.CustomExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


/**
 * 绑定延时队列和延时交换机
 *
 * @author mercury
 */
@Configuration
@ConditionalOnProperty(
        name = {"spring.rabbitmq.enabled"},
        havingValue = "true"
)
public class DelayedQueueConfig {


    /**
     * 声明自定义交换机
     */
    @Bean
    public CustomExchange delayedExchange() {
        Map<String, Object> argument = new ConcurrentHashMap<>(1);
        argument.put("x-delayed-type", "direct");

        return new CustomExchange(DelayedBuilder.DEFAULT_DELAYED_EXCHANGE, "x-delayed-message", true, false, argument);
    }

    /**
     * 声明队列
     */
    @Bean
    public Queue delayedQueue() {
        return new Queue(DelayedBuilder.DEFAULT_DELAYED_QUEEN);
    }

    /**
     * 绑定交换机和队列
     */
    @Bean
    public Binding delayedQueueBinding(@Qualifier("delayedQueue") Queue delayedQueue,
                                       @Qualifier("delayedExchange") CustomExchange delayedExchange) {
        return BindingBuilder
                //绑定队列
                .bind(delayedQueue)
                //交换机
                .to(delayedExchange)
                //根据路由key
                .with(DelayedBuilder.DEFAULT_DELAYED_ROUTING_KEY)
                .noargs();
    }


}
